Implement size_hint for some iterators
authorPhlosioneer <mattmdrr2@gmail.com>
Sun, 1 Apr 2018 10:08:40 +0000 (06:08 -0400)
committerPhlosioneer <mattmdrr2@gmail.com>
Sun, 1 Apr 2018 10:18:42 +0000 (06:18 -0400)
This PR implements size_hints for Deps, DepsNotReplaced, and Members.
These size_hints are used extensively by cargo to allocate Vecs.

Deps, DepsNotReplaced, and RcVecIter also now implement ExactSizeIterator.

src/cargo/core/resolver/resolve.rs
src/cargo/core/workspace.rs

index 08805eba2c2d1fc1bb91a62e731971c4f79edfe7..73d30b1595bb6eb092dac8a44037918aa9914520 100644 (file)
@@ -203,8 +203,19 @@ impl<'a> Iterator for Deps<'a> {
             .and_then(|e| e.next())
             .map(|id| self.resolve.replacement(id).unwrap_or(id))
     }
+
+    fn size_hint(&self) -> (usize, Option<usize>) {
+        match self.edges {
+            // Note: Edges is actually a std::collections::hash_set::Iter, which
+            // is an ExactSizeIterator.
+            Some(ref iter) => iter.size_hint(),
+            None => (0, Some(0))
+        }
+    }
 }
 
+impl<'a> ExactSizeIterator for Deps<'a> {}
+
 pub struct DepsNotReplaced<'a> {
     edges: Option<Edges<'a, PackageId>>,
 }
@@ -215,4 +226,15 @@ impl<'a> Iterator for DepsNotReplaced<'a> {
     fn next(&mut self) -> Option<&'a PackageId> {
         self.edges.as_mut().and_then(|e| e.next())
     }
+
+    fn size_hint(&self) -> (usize, Option<usize>) {
+        match self.edges {
+            // Note: Edges is actually a std::collections::hash_set::Iter, which
+            // is an ExactSizeIterator.
+            Some(ref iter) => iter.size_hint(),
+            None => (0, Some(0))
+        }
+    }
 }
+
+impl<'a> ExactSizeIterator for DepsNotReplaced<'a> {}
index 9377b185cf7864b9c30a1c13e72cc037fb406d22..0c20f63e65e5d6d00cc7928e607af0a4bb16ea24 100644 (file)
@@ -776,6 +776,11 @@ impl<'a, 'cfg> Iterator for Members<'a, 'cfg> {
             }
         }
     }
+
+    fn size_hint(&self) -> (usize, Option<usize>) {
+        let (_, upper) = self.iter.size_hint();
+        (0, upper)
+    }
 }
 
 impl MaybePackage {